package cn.agiledata.bank.linkbank.service;

import cn.agiledata.bank.linkbank.exception.LinkBankException;
import cn.agiledata.bank.linkbank.logic.DigitalSignGeneratable;
import cn.agiledata.bank.linkbank.logic.payment.BankNetPayRequest;
import cn.agiledata.bank.linkbank.logic.payment.UnsPayRequest;

/**
 * 
 * @author maxianbo
 * 
 */
public final class BankNetPayServiceImpl extends BankPayServiceImpl implements
        BankNetPayService {

    /**
     * 订单url前缀。某些银行需要提供一个可以直接查看订单明细的url，如农业银行
     */
    private String orderUrl;

    public void setOrderUrl(String orderUrl) {
        this.orderUrl = orderUrl;
    }

    private String getOrderUrl(String webRootUrl, String orderId) {
        return webRootUrl + this.orderUrl + orderId;
    }

    public BankNetPayRequest getBankNetPayRequest(UnsPayRequest unsPayRequest,
            String transId, String webRootUrl) throws LinkBankException {
        String bankCode = unsPayRequest.getBank().getBankCode();
        BankNetPayRequest bankNetPayRequest = (BankNetPayRequest) getBankPayRequest(
                bankCode, webRootUrl);
        if (bankNetPayRequest == null) {
            throw LinkBankException.UNSUPPORTED_NET_BANK;
        }
        bankNetPayRequest.setOrderId(transId);
        bankNetPayRequest.setOrderUrl(getOrderUrl(webRootUrl, transId));
        bankNetPayRequest.setAmount(unsPayRequest.getAmount());
        bankNetPayRequest.setCurrencyType(unsPayRequest.getCurrencyType());
        bankNetPayRequest.setDate(unsPayRequest.getTime());
        bankNetPayRequest.setRemark(unsPayRequest.getRemark());

        // 校验密钥及预处理网上银行支付请求
        if (bankNetPayRequest instanceof DigitalSignGeneratable) {
            //String cryptoKey = getCryptoKeyOfBank(bankCode);
        	String cryptoKey="123456";
            DigitalSignGeneratable dsGeneratableBankNetPayRequest = (DigitalSignGeneratable) bankNetPayRequest;
            if (!dsGeneratableBankNetPayRequest.validateCryptoKey(cryptoKey)) {
                String macKeyDescription = dsGeneratableBankNetPayRequest
                        .getCryptoKeyDescription();
                throw LinkBankException
                        .getInvalidMacKeyException(macKeyDescription);
            }
            dsGeneratableBankNetPayRequest.generateDigitalSign(cryptoKey);
        }
        bankNetPayRequest.prepare();

        return bankNetPayRequest;
    }

    public boolean validNetBankCode(String bankCode) {
        return validBankCode(getSupportedBanks(), bankCode);
    }
}
